﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.Model;
using System.Data.Objects.DataClasses;
using SCMS.CoreBusinessLogic.Web;
using SCMS.CoreBusinessLogic.ActionFilters;
using SCMS.Reports;
using SCMS.CoreBusinessLogic.TenderAnalysis;
using SCMS.CoreBusinessLogic.Security;
using SCMS.UI.Models;
using OfficeOpenXml.Drawing;
using System.Drawing;
using SCMS.Utils.File;
using System.IO;
using SCMS.Utils.DTOs;
using OfficeOpenXml;

namespace SCMS.UI.Areas.Reports.Controllers
{
    [MyException]
    public class TAController : BaseController
    {

        private ITAnalysisService taService;
        public TAController(IUserContext uc, ITAnalysisService tAervice)
        {
            this.taService = tAervice;
        }

        //
        // GET: /Reports/TA/

        public ActionResult Index(Guid TAid)
        {
            Dictionary<String, String> data = new Dictionary<string, string>();
            Models.TenderAnalysis modelTA = TAExtension.PrepareTAModel(TAid, taService);
            using (var db = new SCMSEntities())
            {
                Model.TenderAnalysi TAentity = db.TenderAnalysis.FirstOrDefault(p => p.Id == TAid);

                data.Add("{DATE}", TAentity.AnalysisDate.FormatDDMMMYYYY());
                data.Add("{TANo}", TAentity.RefNumber);
                data.Add("{ORNo}", TAentity.OrderRequest.RefNumber);
                data.Add("{OR-CURRENCY}", TAentity.OrderRequest.Currency.ShortName);

                GetSupplierDetails(data, modelTA, TAentity);

                data.Add("{PREPARED-BY}", TAentity.Staff1.Person.FirstName + " " + TAentity.Staff1.Person.OtherNames);
                data.Add("{TITLE}", TAentity.Staff1.Designation.Name);
                data.Add("{PREPARE-DATE}", TAentity.PreparedOn.Value.ToString("dd/MM/yyyy h:mm tt"));
                data.Add("{PREPAREDBY-SIGNATURE}", "data:image/png;base64," + Convert.ToBase64String(TAentity.Staff1.Person.SignatureImage));

                String ChoosenSupplierHtml = "";
                ChoosenSupplierHtml = Approved_Rejected(modelTA, ChoosenSupplierHtml);
                ChoosenSupplierHtml = Supplier_Chosen(modelTA, ChoosenSupplierHtml);
                ChoosenSupplierHtml = Addition_Action_Required(modelTA, ChoosenSupplierHtml);
                data.Add("{CHOSEN-SUPPLIER}", ChoosenSupplierHtml);

                String authourisation = "";
                authourisation = AuthName(modelTA, authourisation);
                authourisation = AuthTitle(modelTA, authourisation);
                authourisation = AuthDate(modelTA, authourisation);
                authourisation = AuthSignature(modelTA, authourisation);
                data.Add("{AUTHORISATOIN}", authourisation);

            }

            List<String> options = new List<string>();
            options.Add(" --copies 2 ");
            Byte[] output = WkHtml2Pdf.CreateReport(data, "Tender-Analysis.htm", options);

            return File(output, "application/pdf", "TA_" + DateTime.Now.FormatDDMMMYYYYHHmm());
        }

        public ActionResult SelectedTendersPdf()
        {
            string[] _idList = Request.Form["ids"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            if (_idList.Length > 0)
            {
                List<Guid> idList = new List<Guid>();

                foreach (String i in _idList)
                {
                    idList.Add(new Guid(i));
                }
                List<TenderAnalysisSummary> tenders = taService.Find(idList);

                String html = "<table class='summary default black-borders goods-detail'><thead><tr><th>#</th>";
                html += "<th>TA Ref. No.</th><th>OR Ref. No.</th>";
                html += "<th>Status</th><th>Status Date</th></tr></thead><tbody>";

                int c = 1;


                foreach (TenderAnalysisSummary t in tenders)
                {
                    html += String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>",
                        c, t.RefNo, t.OrderRefNumber, t.Status, t.StatusDate.ToString("dd/MM/yyyy"));
                    c++;
                }

                html += "</tbody></table>";
                Dictionary<String, String> data = new Dictionary<string, string>();
                data.Add("{DETAILS}", html);
                data.Add("{REPORT_DATE}", DateTime.Now.ToString("dd.MM.yyyy"));
                data.Add("{REPORT_TITLE}", "Selected Tender Analysis");


                String fileName = WkHtml2Pdf.CreatePersistedReport(data, "Summary-Tender-Analysis.htm");

                return Content("/Content/tmp_reports/" + fileName);
            }

            return Content("#N/A");
        }


        public ActionResult SelectedTendersExcel()
        {

            string[] _idList = Request.Form["ids"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            if (_idList.Length > 0)
            {
                List<Guid> idList = new List<Guid>();

                foreach (String i in _idList)
                {
                    idList.Add(new Guid(i));
                }
                List<TenderAnalysisSummary> tenders = taService.Find(idList);


                using (var stream = new MemoryStream())
                {
                    using (var xlPackage = new ExcelPackage())
                    {
                        var ws = xlPackage.Workbook.Worksheets.Add("Tenders");
                        ws.SetValue(2, 1, "Supply Chain Management Report");

                        ws.SetValue(4, 1, "Report:");
                        ws.SetValue(6, 1, "Date:");

                        ws.SetValue(4, 2, "Selected Tenders");
                        ws.SetValue(6, 2, DateTime.Now.ToString("dd.MM.yyyy"));

                        int row = 10;
                        ws.SetValue(row, 1, "TA Ref. No.");
                        ws.SetValue(row, 2, "OR Ref. No.");
                        ws.SetValue(row, 3, "Prepared By");
                        ws.SetValue(row, 4, "Status");
                        ws.SetValue(row, 5, "Status Date");

                        ws.Cells[2, 1, 2, 5].Merge = true; //Merge columns start and end range
                        ws.Cells[2, 1, 10, 5].Style.Font.Bold = true;

                        row++;
                        foreach (TenderAnalysisSummary t in tenders)
                        {
                            ws.SetValue(row, 1, t.RefNo);
                            ws.SetValue(row, 2, t.OrderRefNumber);
                            ws.SetValue(row, 3, t.PreparedBy);
                            ws.SetValue(row, 4, t.Status);
                            ws.SetValue(row, 5, t.StatusDate.ToString("dd.MM.yyyy"));

                            row++;
                        }

                        Bitmap image = ImageUtility.GetLogosImage();
                        ExcelPicture picture = null;

                        if (image != null)
                        {
                            picture = ws.Drawings.AddPicture("logo-" + (new Guid()).ToString(), image);
                            picture.From.Column = 3;
                            picture.From.Row = 2;
                            picture.SetSize(91, 90);
                        }

                        for (int c = 1; c < 6; c++)
                        {
                            ws.Column(c).AutoFit();
                        }

                        xlPackage.SaveAs(stream);
                    }


                    String tmpFilename = Guid.NewGuid().ToString() + ".xlsx";

                    String fullExcelFilePath = Server.MapPath(Url.Content("~/Content/tmp_reports/")) + tmpFilename;

                    FileStream eFile = new FileStream(fullExcelFilePath, FileMode.Create);

                    stream.WriteTo(eFile);
                    eFile.Close();
                    return Content("/Content/tmp_reports/" + tmpFilename);
                }

            }

            return Content("#N/A");
        }

        private static String AuthSignature(Models.TenderAnalysis modelTA, String authourisation)
        {
            authourisation += "<tr><td class=\"gridheader\">Signature:</td><td>";
            if (modelTA.TenderEvaluators.Count > 0 && modelTA.TenderEvaluators[0].Priority != 3 && modelTA.TenderEvaluators[0].HasApproved != null)
                if (modelTA.TenderEvaluators[0].Staff.Person.SignatureImage != null)
                    authourisation += string.Format("<img src=\"{0}\" alt=\"\" style=\"max-width: 100px;\" />", "data:image/png;base64," + Convert.ToBase64String(modelTA.TenderEvaluators[0].Staff.Person.SignatureImage));
            authourisation += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 1 && modelTA.TenderEvaluators[1].Priority != 3 && modelTA.TenderEvaluators[1].HasApproved != null)
                if (modelTA.TenderEvaluators[1].Staff.Person.SignatureImage != null)
                    authourisation += string.Format("<img src=\"{0}\" alt=\"\" style=\"max-width: 100px;\" />", "data:image/png;base64," + Convert.ToBase64String(modelTA.TenderEvaluators[1].Staff.Person.SignatureImage));
            authourisation += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 2 && modelTA.TenderEvaluators[2].Priority == 3 && modelTA.TenderEvaluators[2].HasApproved != null)
                if (modelTA.TenderEvaluators[2].Staff.Person.SignatureImage != null)
                    authourisation += string.Format("<img src=\"{0}\" alt=\"\" style=\"max-width: 100px;\" />", "data:image/png;base64," + Convert.ToBase64String(modelTA.TenderEvaluators[2].Staff.Person.SignatureImage));
            authourisation += "</td><tr>";
            return authourisation;
        }

        private static String AuthDate(Models.TenderAnalysis modelTA, String authourisation)
        {
            authourisation += "<tr><td class=\"gridheader\">Date:</td><td>";
            if (modelTA.TenderEvaluators.Count > 0 && modelTA.TenderEvaluators[0].Priority != 3 && modelTA.TenderEvaluators[0].HasApproved != null)
                authourisation += modelTA.TenderEvaluators[0].DateApproved.Value.ToString("dd/MM/yyyy h:mm tt");
            authourisation += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 1 && modelTA.TenderEvaluators[1].Priority != 3 && modelTA.TenderEvaluators[1].HasApproved != null)
                authourisation += modelTA.TenderEvaluators[1].DateApproved.Value.ToString("dd/MM/yyyy h:mm tt");
            authourisation += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 2 && modelTA.TenderEvaluators[2].Priority == 3 && modelTA.TenderEvaluators[2].HasApproved != null)
                authourisation += modelTA.TenderEvaluators[2].DateApproved.Value.ToString("dd/MM/yyyy h:mm tt");
            authourisation += "</td><tr>";
            return authourisation;
        }

        private static String AuthTitle(Models.TenderAnalysis modelTA, String authourisation)
        {
            authourisation += "<tr><td class=\"gridheader\">Title:</td><td>";
            if (modelTA.TenderEvaluators.Count > 0 && modelTA.TenderEvaluators[0].Priority != 3)
                authourisation += modelTA.TenderEvaluators[0].Staff.Designation.Name;
            authourisation += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 1 && modelTA.TenderEvaluators[1].Priority != 3)
                authourisation += modelTA.TenderEvaluators[1].Staff.Designation.Name;
            authourisation += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 2 && modelTA.TenderEvaluators[2].Priority == 3)
                authourisation += modelTA.TenderEvaluators[2].Staff.Designation.Name;
            authourisation += "</td><tr>";
            return authourisation;
        }

        private static String AuthName(Models.TenderAnalysis modelTA, String authourisation)
        {
            authourisation += "<tr><td class=\"gridheader\">Name:</td><td>";
            if (modelTA.TenderEvaluators.Count > 0 && modelTA.TenderEvaluators[0].Priority != 3)
                authourisation += modelTA.TenderEvaluators[1].Staff.Person.FirstName + " " + modelTA.TenderEvaluators[0].Staff.Person.OtherNames;
            authourisation += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 1 && modelTA.TenderEvaluators[1].Priority != 3)
                authourisation += modelTA.TenderEvaluators[1].Staff.Person.FirstName + " " + modelTA.TenderEvaluators[1].Staff.Person.OtherNames;
            authourisation += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 2 && modelTA.TenderEvaluators[2].Priority == 3)
                authourisation += modelTA.TenderEvaluators[2].Staff.Person.FirstName + " " + modelTA.TenderEvaluators[2].Staff.Person.OtherNames;
            authourisation += "</td><tr>";
            return authourisation;
        }

        private static String Addition_Action_Required(Models.TenderAnalysis modelTA, String ChoosenSupplierHtml)
        {
            ChoosenSupplierHtml += "<tr><td>Additional action Required</td><td>";
            if (modelTA.TenderEvaluators.Count > 0 && modelTA.TenderEvaluators[0].Priority != 3 && modelTA.TenderEvaluators[0].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[0].Remarks;
            ChoosenSupplierHtml += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 1 && modelTA.TenderEvaluators[1].Priority != 3 && modelTA.TenderEvaluators[1].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[1].Remarks;
            ChoosenSupplierHtml += "</td><td>";
            if (modelTA.TenderEvaluators.Count > 2 && modelTA.TenderEvaluators[2].Priority == 3 && modelTA.TenderEvaluators[2].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[2].Remarks;
            ChoosenSupplierHtml += "</td></tr>";
            return ChoosenSupplierHtml;
        }

        private static String Supplier_Chosen(Models.TenderAnalysis modelTA, String ChoosenSupplierHtml)
        {
            ChoosenSupplierHtml += "<tr><td>Supplier Chosen</td><td align=\"center\">";
            if (modelTA.TenderEvaluators.Count > 0 && modelTA.TenderEvaluators[0].Priority != 3 && modelTA.TenderEvaluators[0].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[0].RecommendedSupplierId != null ? modelTA.TenderEvaluators[0].Supplier.Name : "";
            ChoosenSupplierHtml += "</td><td align=\"center\">";
            if (modelTA.TenderEvaluators.Count > 1 && modelTA.TenderEvaluators[1].Priority != 3 && modelTA.TenderEvaluators[1].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[1].RecommendedSupplierId != null ? modelTA.TenderEvaluators[1].Supplier.Name : "";
            ChoosenSupplierHtml += "</td><td align=\"center\">";
            if (modelTA.TenderEvaluators.Count > 2 && modelTA.TenderEvaluators[2].Priority == 3 && modelTA.TenderEvaluators[2].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[2].RecommendedSupplierId != null ? "<font color=\"blue\"><h4>" + modelTA.TenderEvaluators[2].Supplier.Name + "</h4></font>" : "";
            ChoosenSupplierHtml += "</td></tr>";
            return ChoosenSupplierHtml;
        }

        private static String Approved_Rejected(Models.TenderAnalysis modelTA, String ChoosenSupplierHtml)
        {
            ChoosenSupplierHtml += "<tr><td>Approved / Rejected</td><td align=\"center\">";
            if (modelTA.TenderEvaluators.Count > 0 && modelTA.TenderEvaluators[0].Priority != 3 && modelTA.TenderEvaluators[0].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[0].HasApproved.Value ? "<font color=\"green\"><b>Approved</b></font>" : "<font color=\"red\"><b>Rejected</b></font>";
            ChoosenSupplierHtml += "</td><td align=\"center\">";
            if (modelTA.TenderEvaluators.Count > 1 && modelTA.TenderEvaluators[1].Priority != 3 && modelTA.TenderEvaluators[1].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[1].HasApproved.Value ? "<font color=\"green\"><b>Approved</b></font>" : "<font color=\"red\"><b>Rejected</b></font>";
            ChoosenSupplierHtml += "</td><td align=\"center\">";
            if (modelTA.TenderEvaluators.Count > 2 && modelTA.TenderEvaluators[2].Priority == 3 && modelTA.TenderEvaluators[2].HasApproved != null)
                ChoosenSupplierHtml += modelTA.TenderEvaluators[2].HasApproved.Value ? "<font color=\"green\"><b>Authorized</b></font>" : "<font color=\"red\"><b>Rejected</b></font>";
            ChoosenSupplierHtml += "</td></tr>";
            return ChoosenSupplierHtml;
        }

        private static void GetSupplierDetails(Dictionary<String, String> data, Models.TenderAnalysis modelTA, Model.TenderAnalysi TAentity)
        {
            String suppliersHtml = "";
            foreach (string item in modelTA.SupplierName)
                suppliersHtml += "<th align=\"center\">" + item + "</th>";
            data.Add("{TASUPPLIER}", suppliersHtml);

            String TenderItemHtml = "";
            int cols = 1 + modelTA.SupplierName.Count;
            foreach (var tenderItem in modelTA.TBiderQuotes)
            {
                TenderItemHtml += "<tr><td>" + tenderItem.ItemDescription + "</td>";
                foreach (var subItem in tenderItem.UnitCost)
                    TenderItemHtml += "<td align=\"right\">" + subItem.ToString("#,##0.00") + "</td>";
                TenderItemHtml += "</tr>";
            }

            if (modelTA.TransportCost.Count > 0)
            {
                TenderItemHtml += "<tr><td>Transport Cost</td>";
                foreach (var transportCostitem in modelTA.TransportCost)
                    TenderItemHtml += "<td align=\"right\">" + transportCostitem.ToString("#,##0.00") + "</td>";
                TenderItemHtml += "</tr>";
            }

            TenderItemHtml += "<tr><td><b>Total Cost</b></td>";
            foreach (var totalCostitem in modelTA.TotalCost)
                TenderItemHtml += "<td align=\"right\">" + totalCostitem.ToString("#,##0.00") + "</td>";
            TenderItemHtml += "</tr>";

            data.Add("{TENDER-ITEM}", TenderItemHtml);
            data.Add("{COLSPAN}", cols.ToString());


            String TermsAndConditionsHtml = "";
            if (modelTA.ShippingTerm.Count > 0)
            {
                TermsAndConditionsHtml += "<tr><td>Shipping Term</td>";
                foreach (var shipingTerm in modelTA.ShippingTerm)
                    TermsAndConditionsHtml += "<td align=\"right\">" + shipingTerm + "</td>";
                TermsAndConditionsHtml += "</tr>";
            }

            if (modelTA.DeliveryTime.Count > 0)
            {
                TermsAndConditionsHtml += "<tr><td>Delivery Time</td>";
                foreach (var DeliveryTime in modelTA.DeliveryTime)
                    TermsAndConditionsHtml += "<td align=\"right\">" + DeliveryTime.ToString("dd/MM/yyyy") + "</td>";
                TermsAndConditionsHtml += "</tr>";
            }

            if (modelTA.Warrant.Count > 0)
            {
                TermsAndConditionsHtml += "<tr><td>Warranty</td>";
                foreach (var warranty in modelTA.Warrant)
                    TermsAndConditionsHtml += "<td align=\"right\">" + warranty + "</td>";
                TermsAndConditionsHtml += "</tr>";
            }

            if (modelTA.TermzOfPayment.Count > 0)
            {
                TermsAndConditionsHtml += "<tr><td>Terms of Payment</td>";
                foreach (var termOfPayment in modelTA.TermzOfPayment)
                    TermsAndConditionsHtml += "<td align=\"right\">" + termOfPayment + "</td>";
                TermsAndConditionsHtml += "</tr>";
            }

            if (modelTA.others.Count > 0)
            {
                TermsAndConditionsHtml += "<tr><td>Other</td>";
                foreach (var other in modelTA.others)
                    TermsAndConditionsHtml += "<td align=\"right\">" + other + "</td>";
                TermsAndConditionsHtml += "</tr>";
            }

            data.Add("{TERMS-CONDITIONS}", TermsAndConditionsHtml);
            data.Add("{RECOMENDATIONS}", TAentity.Recommendation);
        }

    }
}
